from typing import List

from fastapi import status, APIRouter
from fastapi.exceptions import HTTPException

from .models import PostIn_Pydantic, Post_Pydantic, Post

app = APIRouter()


# response_model会限制输出数据为定义的pydantic模型,并校验转化为所定义的数据格式
@app.post('/posts', response_model=Post_Pydantic, status_code=status.HTTP_201_CREATED)
async def create_post(post: PostIn_Pydantic):
    # exclude_unset设置为True表示如果用户没有传改字段，不会使用默认字段和其默认值
    # https://fastapi.tiangolo.com/tutorial/body-updates/?h=exclude_unset#using-pydantics-exclude_unset-parameter
    post_obj = await Post.create(**post.dict(exclude_unset=True))
    # 返回Pydantic模型对象
    return await Post_Pydantic.from_tortoise_orm(post_obj)


@app.get('/posts', response_model=List[Post_Pydantic])
async def get_posts():
    return await Post_Pydantic.from_queryset(Post.all())


@app.get('/posts/{post_id}', response_model=Post_Pydantic)
async def get_post(post_id: int):
    return await Post_Pydantic.from_queryset_single(Post.get(id=post_id))


@app.put('/posts/{post_id}', response_model=Post_Pydantic)
async def update_post(post_id: int, post: PostIn_Pydantic):
    await Post.filter(id=post_id).update(**post.dict(exclude_unset=True))
    # 返回更新后的数据
    return await Post_Pydantic.from_queryset_single(Post.get(id=post_id))


@app.delete('/posts/{post_id}', status_code=status.HTTP_204_NO_CONTENT)
async def delete_post(post_id: int):
    deleted_post = await Post.filter(id=post_id).delete()
    if not deleted_post:
        raise HTTPException(status_code=404, detail=f'Post {post_id} not found')
    return {}
